<?php
namespace submodule\base;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;


use submodule\models\Models;
use submodule\models\ModelsField;
use common\components\Tree;
use base\YiiMobo;

use \common\models\DIYModel;

class BaseModelsFormController extends BaseSubmoduleController
{

    public $categorys;
	
	public $uid;
	
	public $model;
	
	public $model_data;
	
	public $data;
	
	public $models;//模型参数配置

	public $allowinput_fields;//允许后台录入的字段
	
	public $fields;//模型字段
	
	public $modelid;
	
	public $tablename;
	public $data_tablename;
	
	public $primarykey = 'id';
	
	
	public $default_field = array('id', 'modelid', 'addtime', 'updatetime', 'listorder');
	
	public $viewFiles;
	
	public $controllerUrl;
	
	
	
	public function init(){
		
		parent::init();
		if (isset($_REQUEST['modelid'])){
			$this->modelid = $_REQUEST['modelid'];
			$this->models = Yii::$app->FileCache->get('backend_models_'.$this->modelid);
			//print_r($this->models['models']);exit;
			$this->allowinput_fields = $this->models['allowinput_fields'];
			$this->fields = $this->models['fields'];
			$this->primarykey=  $this->models['primarykey'];
			
			//$this->models['models'] = $this->models['models']['models'];
			$this->tablename = '{{%'.$this->models['models']['tablename'].'}}';
			
			$this->data_tablename = '{{%'.$this->models['models']['tablename'].'_data}}';
		}
		$this->controllerUrl = [
		    'index'=> $this->module->id.'/index/index',
			'create' => $this->module->id.'/index/create',
			'update'=> $this->module->id.'/index/update',
			'batch'=> $this->module->id.'/index/batch',
			'view'=> $this->module->id.'/index/view',
			'delete'=> $this->module->id.'/index/delete',
			'status'=> $this->module->id.'/index/status'
		];
				//视图
		$this->viewFiles = [
		    'index'=> @$this->models['models']['setting']['index']['views'],
		    'form'=> @$this->models['models']['setting']['index']['views'],

		];
		
		
		
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
     return array( 
        array('auth.filters.AuthFilter'),
            );
        }

    public function getViewFiles($action = 'index'){
		$viewfile = $this->viewFiles[$action];
		if (!$viewfile){
			$viewfile = "@submodule/views/models-form/modelsform_".$action;
		}
		return $viewfile;
		
	}
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate($parentid = 0)
	{
		//print_r($this->fields);exit;
		$sql='select * from '.$this->tablename.' where id=0';
	
		$model = Yii::$app->getDb()->getTableSchema($this->tablename);
		$model =  (object)null;
		foreach (Yii::$app->getDb()->getTableSchema($this->tablename)->columns as $column) {
            $value = $column->defaultValue ? $column->defaultValue : '';
            $model->{$column->name} = $value;
			$model->attributes[$column->name] = $value;
            
        }
		
		if($this->data_tablename){
			foreach (Yii::$app->getDb()->getTableSchema($this->data_tablename)->columns as $column) {
				$value = $column->defaultValue ? $column->defaultValue : '';
				$model->{$column->name} = $value;
				$model->attributes[$column->name] = $value;
				
			}
		}else if($this->models['models']['type'] == 'category'){
			$model->parentid = $model->attributes['parentid'] = $parentid;
		}
        if(isset($_POST['Models']))
		{
			$this->SaveForm();
		}
		$this->data['id'] = '';
		foreach($this->fields as $k=>$v){
		    $this->data[$v['field']] = isset($setting['defaultvalue']) ? $setting['defaultvalue'] : '';
		}
		//print_r($this->data);exit;
		return $this->render($this->getViewFiles('form'), [
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
			'allowinput_fields'=> $this->allowinput_fields
		]);
	}
	
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionUpdate($id)
	{
        if(isset($_POST['Models']))
		{
			$this->SaveForm($id);
		}else{
			
		}
		
		$sql="SELECT * FROM {$this->tablename} a";
		if($this->data_tablename) $sql .= " inner join {$this->data_tablename} b on a.`{$this->primarykey}` = b.`{$this->primarykey}`";
		$sql .= " where a.`{$this->primarykey}` = $id";
		
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if (!$data){
            $this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '数据不存在', 'timeout'=> 3000]);
		}
		$model = (object)$data;
		$model->attributes = $data;

		return $this->render($this->getViewFiles('form'), [
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
		]);
	}

	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionView($id)
	{
		$sql="SELECT * FROM $this->tablename a";
		if($this->data_tablename) $sql .= " inner join $this->data_tablename b on a.{$this->primarykey} = b.{$this->primarykey}";
		$sql .= " where a.{$this->primarykey} = $id";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if (!$data) $this->null_OperTips();
		$model = $data;
		
        $viewfile = $this->getViewFiles('view');
        //print_r($this->fields);exit;
		return $this->render($viewfile,[
		    'model'=> $model,
		    'models'=> $this->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->fields,
		]);
	}

	/**
	 * 保存表单提交数据
     * 
	 */
	public function SaveForm($id = ''){
		$tableName = $this->models['models']['tablename'];
		$save = $this->loadSubmoduleExtend('Backend', $tableName, $this->models, $_POST['Models'], $this->modelid);
		$data = [];
		$data_data = [];
		$fields = [];
		foreach($this->fields as $k=>$v){
			$fields[] = $v['field'];
			if ($v['field'] != $this->primarykey){
				$defaultvalue = isset($v['setting']['defaultvalue']) ? $v['setting']['defaultvalue'] : NULL;
				if (!$v['allowinput']){
                    $value = $defaultvalue;
				}else{
				    $value = isset($_POST['Models'][$v['field']]) ? $_POST['Models'][$v['field']] : $defaultvalue;
			    }
				if ($v['formtype'] == 'checkbox'){
					$value = $value ? $this->jsons_encode($value) : '';
				}
			    
				if (method_exists($save, $v['field'].'Save')){
					$savefunction = $v['field'].'Save';
					$value = $save->$savefunction($v['fieldid'], $v['field']);
				}
				if($v['primarytable']){
                    $data[$v['field']] = $value;
				}else{
					$data_data[$v['field']] = $value;
				}
			}
		}
		//$data['modelid'] = $this->modelid; 
		if (in_array('updatetime', $fields)) $data['updatetime'] = time(); 
		if (!$id){
			if (in_array('addtime', $fields)) $data['addtime'] = time(); 
		}else{
            if (in_array('addtime', $fields)) unset($data['addtime']);
		}
		$connection = Yii::$app->db;
        $connection->open();
		//print_r($data);exit;
		
		//update
		if ($id){
			$insertid = $id;
			$connection->createCommand()->update($this->tablename, $data, $this->primarykey.' = '.$id)->execute();
			if($this->data_tablename){
				$connection->createCommand()->update($this->data_tablename, $data_data, $this->primarykey.' = '.$id)->execute();
			}
		//insert
		}else{
		    $connection->createCommand()->insert($this->tablename, $data)->execute();
			$insertid = $data_data[$this->primarykey] = $connection->getLastInsertID();
			if($this->data_tablename){
				$connection->createCommand()->insert($this->data_tablename, $data_data)->execute();
			}
		}


		try{
			if($this->models['models']['type'] == 'category'){
				$depth = $this->CategoryDepth($insertid);
			    $connection->createCommand()->update($this->tablename, ['depth'=> join(',', $depth)], 'id = '.$insertid)->execute();
			    $children = $this->CategoryChildren($insertid);
			    $connection->createCommand()->update($this->tablename, ['children'=> $children], 'id = '.$insertid)->execute();
				$this->updateCategoryCache();
			}
			$data['backurl'] = $this->createUrl([$this->controllerUrl['index'], 'modelid'=>$this->modelid]);
			if(Yii::$app->request->getIsAjax()){
				
				$this->echojson($data);
			}else{
			    $this->OperTips($data['backurl']);
			}
		}catch (Exception $e){
			var_dump($e);
		}
	}
		
		
	public function Save($data, $savefunction){
		$function = create_function('$a','
			    $this = $data[$k];
			    $savefunction
			');
		
	}
		/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){
		if ($this->models['models']['type'] == 'category'){
			$this->actionIndexCategory();
			
		}else if ($this->models['models']['type'] == 'content'){
		    $this->actionIndexContent();	
		}else{
		    $this->actionIndexContent();	
		}
	}
	
	public function actionIndexContent(){
		$search = [];
		$search['keyword'] = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : NULL;
        $search['starttime'] = isset($_REQUEST['starttime']) ? $_REQUEST['starttime'] : NULL;
        $search['endtime'] = isset($_REQUEST['endtime']) ? $_REQUEST['endtime'] : NULL;


		$indexFields = $this->indexFields();
        $fields = ["a.`{$this->primarykey}`"];
        foreach($indexFields as $k=>$v){
            $fields[] = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';    
        }
        $fields = join(', ',$fields);
		$sql = "SELECT $fields FROM $this->tablename a";
		if (strpos($fields,'b.`')){
            $sql .= " inner join $this->data_tablename b on a.`{$this->primarykey}` = b.`{$this->primarykey}`";
		}
		$sql .= ' where 1 = 1';
		if ($search['keyword']){
			foreach($this->fields as $v){
				if (isset($v['setting']['search']) && $v['setting']['search']){
					$field = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';
					$sql .= " and $field like '%".$search['keyword']."%'";
				}
			}
		}
		if ($search['starttime']) $sql .= " and a.`addtime` >= ".strtotime($search['starttime']);
		if ($search['endtime']) $sql .= " and a.`addtime` <= ".strtotime($search['endtime']);

        
        $orderby = isset($_REQUEST['orderby']) ? $_REQUEST['orderby'] : "a.`{$this->primarykey}` desc";
        $sql .= ' order by '.$orderby;
        $viewfile = $this->getViewFiles('index');
		echo $this->render($viewfile, array_merge(YiiMobo::pageRows($sql), [
		    'search'=>$search,
		    'orderby' => explode(' ',$orderby),
		    'models' => $this->models,
			'modelid' => $this->modelid,
			'indexFields' => $this->indexFields()
		]));
		
	}
	
	public function actionGetData($modelid, $parentid = 0){
		$sql="SELECT * FROM $this->tablename where parentid = $parentid order by listorder asc,id asc";
		$data['modelid'] = $modelid;
		$data['data'] = Yii::$app->db->createCommand($sql)->queryAll();
		$data['depth'] = $this->CategoryDepth($parentid);
		$data['count'] = count($data['data']) - 1;
		foreach($data as $k=>$v){
			
			//$data[$k]['depth'] = $this->CategoryDepth($v['id']);
		    	
		}
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	
	public function CategoryDepth($myid, &$newarr = []){
		//global $newarr;
		$sql="SELECT parentid FROM $this->tablename where id = $myid";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if(!$data){
			//$newarr = [];
			 return false;
		}
		$parentid = $data['parentid'];
        $newarr[] = $parentid;
		
		if($parentid){
		    $this->CategoryDepth($parentid, $newarr);
		}
        
		return array_reverse($newarr);
	}
	public function CategoryChildren($myid){
		$sql="SELECT id FROM $this->tablename where FIND_IN_SET('$myid', depth)";
		return (int)Yii::$app->db->createCommand($sql)->queryAll();
	}

	public function actionDelete($modelid, $id){
		if ($this->models['models']['type'] == 'category'){
			$sql="SELECT id FROM $this->tablename where parentid = $id";
			if(Yii::$app->db->createCommand($sql)->queryOne()){
				$this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '不能删除有子级分类的数据', 'timeout'=> 3000]);
			}
			
		}else if ($this->models['models']['type'] == 'content'){
			$return = Yii::$app->db->createCommand()->delete($this->data_tablename, 'id = '.$id)->execute();
		}
		    $return = Yii::$app->db->createCommand()->delete($this->tablename, 'id = '.$id)->execute();
		if ($this->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
    /**
     * 更改状态设置
     * 
     */
    public function actionStatus($id, $field = 'status', $status) {
        $sql = "update $this->tablename set `$field` = $status where id = '$id'";
        Yii::$app->db->createCommand($sql)->query();
		$this->updateCategoryCache();
    }
	
	/**
	* 更新分类数据缓存
	*
	*/
    public function updateCategoryCache($return = false){
    	if ($this->models['models']['type'] != 'category') return false;
        if (intval($this->models['models']['setting']['index']['ajax']) == 0){
			$sql="SELECT * FROM $this->tablename order by listorder asc, id desc";
			$data = Yii::$app->db->createCommand($sql)->queryAll();
			
			$array = array();
			foreach($data as $k=>$v){
				$depth = $this->CategoryDepth($v['id']);
				
				$v['depth'] = $depth;
				$array[$v['id']] = $v;
				Yii::$app->db->createCommand()->update($this->tablename, ['depth'=>join(',', $depth)], 'id = '.$v['id'])->execute();
				
			}
			Yii::$app->FileCache->set("models_data_".$this->modelid, $array);
			if ($return) return $array;
		}
	}
	
	public function formFields(){
		foreach($this->fields as $v){
			if (!in_array($v['field'], $this->default_field)){
				$data[] = $v;
			}
		}
		return $data;
		
	}
	
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch(){
        $ids = isset($_POST['checked_id']) ? $_POST['checked_id'] : NULL;
        if(isset($_POST['batch_delete']) && $ids){
            if (isset($_POST['batch_delete'])){
                if ($this->models['models']['type'] == 'content'){
					Yii::$app->db->createCommand()->delete($this->tablename, ['id'=>$ids])->execute();
					$return = Yii::$app->db->createCommand()->delete($this->data_tablename, ['id'=>$ids])->execute();
				}else if ($this->models['models']['type'] == 'category'){
					$catid = [];
					foreach($ids as $id){
						$sql="SELECT id FROM $this->tablename where parentid = $id";
						if(!Yii::$app->db->createCommand($sql)->queryOne()){
							$catid[] = $id;
						}
					}
					Yii::$app->db->createCommand()->delete($this->tablename, ['id'=>$catid])->execute();
				}
		        
		
            }
			
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorder']) foreach($_POST['listorder'] as $id=>$listorder){
				if (is_numeric($id)){
					$data = [
						'name' => $_POST['name'][$id],
						'listorder'=>intval($listorder),
					
					];
					Yii::$app->db->createCommand()->update($this->tablename, $data, 'id = '.$id)->execute();
				}
			}
		}else if(isset($_POST['batch_create'])){
			if(isset($_POST['add_ame'])) foreach($_POST['add_ame'] as $k=>$v){
				if (!$v) continue;
				$data = [
				    'name' => $v,
					'parentid' => $_POST['add_pid'][$k],
					'listorder' => $_POST['add_listorder'][$k],
				];
				Yii::$app->db->createCommand()->insert($this->tablename, $data)->execute();
				$insertid = Yii::$app->db->getLastInsertID();
				if($this->models['models']['type'] == 'category'){
					$depth = $this->CategoryDepth($insertid);
					Yii::$app->db->createCommand()->update($this->tablename, ['depth'=> join(',', $depth)], 'id = '.$insertid)->execute();	
					//exit($depth);				
				}
			}
		}
		
        if ($this->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
	public function actionConfig($modelid, $module)
	{
		$tablename = 'submodule_module';
		if(isset($_POST['Module']))
		{
			$data['setting'] = json_encode($_POST['Module'], JSON_UNESCAPED_UNICODE);
			Yii::$app->db->createCommand()->update($tablename, $data, "module = '$module'")->execute();
			$this->OperTips();
		}
        $sql="SELECT setting FROM `$tablename` where module = '$module'";
		$model = json_encode(Yii::$app->db->createCommand($sql)->queryOne(), true);
		return $this->render('config',[
		    'modelid' => $modelid,
			'module'=> $module,
			'model'=>$model
		]);
	}
	
	
	public function indexFields(){
		$fields = array();
		foreach($this->models['models']['setting']['index']['listorder'] as $k=>$val){
			if(isset($this->fields[$val]) && in_array($this->fields[$val]['field'], $this->models['models']['setting']['index']['fields'])){
				$value = $this->fields[$val];
				//$value['_values'] = 
				$fields[$val] = $value;
			}
		}
		return $fields;
	}
	
	
	public function listorderFields(){
	    
	    $fields = array_diff($this->fields, $this->models['models']['setting']['index']['listorder']);
		
	}
	

	


}
